#!/usr/bin/env python3
#coding:utf-8

__author__ = 'xmxoxo<xmxoxo@qq.com>'


'''
文件名： mq_sender.py 

消息发送端，模拟发送随机消息到指定频道；可指定消息频率；

# 每隔3秒发送随机消息到频道：fj.xm.362.normal
python mq_client.py --delay=3 --channel=fj.xm.362.normal

'''
from baselibs import *
from mq_lib import *

parser = argparse.ArgumentParser(description='MQ client')
parser.add_argument('--channel', type=str, default='', help='发送的频道')
parser.add_argument('--repeat', type=int, default=1, help='是否允许重复消费，默认1=允许')
args = parser.parse_args()
t_channel = args.channel
repeat = args.repeat


# 连接MQ 
print('正在连接MQ服务器: %s:%s...' % (rabbit_ip, rabbit_port) )
mq = MQ(ip=rabbit_ip, port=rabbit_port)
mq.login(rabbit_user, rabbit_pwd)

# 定义消息 
msg = MSG()

# 延迟时间变化区间，1-5秒，两个消息之间的时间间隔，随机变化
delay_area = 1, 5
# 基数，模拟这个数值不断变化
base = 18

# 区域列表
#areas = ['FuZhou','XiaMen','ZhangZhou','NanPing']
areas = ['fz','xm','zz','np']

# 终端号个数，随机生成
idx = 300

ntxt = t_channel if t_channel!='' else '随机频道'
print('正在启动消息发送，发送频道:', ntxt)

while 1:
    
    if t_channel == "":
        # 随机选择区域
        c_area = random.choice(areas)
        # 随机生成终端ID
        c_idx = random.randrange(idx)
        channel = 'fj.%s.%d' % (c_area, c_idx)
    else:
        channel = t_channel

    # msg.add("channel", channel)

    # 生成变化的温度值
    base = base + random.random()-0.5
    message = str(round(base, 2))
    msg.add("Temperature", message)

    # 生成消息ID,用于处理消息重复消费，2023/9/14    
    msgid = msg.rand_id("msgid", prekey='test_')
    if repeat==0:
        msg.add("repeat", 0)
    
    '''
    print('repeat:', repeat)
    print('repeat:', repeat==0)
    print('msg:', msg)
    '''

    # 发送消息
    mq.send(channel, str(msg))
    
    # 随机停止时间: [delay-2, delat)
    delays = delay_area[0] + (delay_area[1] - delay_area[0]) * random.random()
    print(" [x] [%r] Sent:[%s] delay:%f" % (channel, str(msg), delays))
    time.sleep(delays)


if __name__ == '__main__':
    pass

